<template>
  <view class="leave-school-apply">
    <!-- 顶部返回区域 -->
    <view class="back-area" @click="goBack">
      <text class="back-icon">←</text>
      <text class="back-text">返回</text>
    </view>

    <!-- 提示栏 -->
    <view class="tip-bar">
      <text class="tip-text">留校申请需要审批，请认真做留校计划！</text>
    </view>

    <!-- 选项卡 -->
    <view class="tabs">
      <view class="tab-item active" @click="goToPage2('leave')">离校申请</view>
      <view class="tab-item" @click="goToPage3">留校申请</view>
      <view class="tab-item" @click="goToPage4">返校登记</view>
    </view>

    <!-- 行程信息容器 -->
    <view class="trip-container">
      <!-- 行程信息卡片 -->
      <view v-for="(trip, index) in trips" :key="trip.id" class="form-section trip-card">
        <view class="trip-card-header">
          <text class="section-title">行程信息{{ index + 1 }}</text>
          <view class="minus-btn" @click="removeTrip(index)" v-if="trips.length > 1">-</view>
        </view>

        <text class="section-desc">请填写当前行程的详细信息</text>

        <!-- 交通工具 -->
        <view class="form-item">
          <text class="label">交通工具*</text>
          <template v-if="index === 0">
            <view class="dict-selector" @click="showTransportDict = true">
              <text class="selected-value">{{ selectedTransport || '请选择交通工具' }}</text>
              <text class="select-icon">▼</text>
            </view>
          </template>
          <textarea
              v-else
              placeholder="请输入交通工具（如：火车、汽车）"
              class="textarea"
              :value="trip.transport"
              @input="trip.transport = $event.target.value"
          ></textarea>
        </view>

        <!-- 交通信息 -->
        <view class="form-item">
          <text class="label">交通信息*</text>
          <textarea
              placeholder="请输入车牌号、火车班次、航班号"
              class="textarea"
              :value="trip.transportInfo"
              @input="trip.transportInfo = $event.target.value"
          ></textarea>
        </view>

        <!-- 出发地/出发站点 -->
        <view class="form-item">
          <text class="label">{{ index === 0 ? '出发站点' : '出发地' }}*</text>
          <textarea
              v-if="index === 0"
              placeholder="请输入出发站点"
              class="textarea"
              :value="trip.departure"
              @input="trip.departure = $event.target.value"
          ></textarea>
          <template v-else>
            <view class="cascade-selector" @click="openCascadeSelector('departure', index)">
              <text class="selected-value">
                {{ trip.departureProvince && trip.departureCity && trip.departureDistrict
                  ? `${trip.departureProvince}-${trip.departureCity}-${trip.departureDistrict}`
                  : '请选择省/市/区' }}
              </text>
              <text class="select-icon">▼</text>
            </view>
          </template>
        </view>

        <!-- 目的地 -->
        <view class="form-item">
          <text class="label">目的地*</text>
          <textarea
              v-if="index === 0"
              placeholder="请选择省/市/区(县)"
              class="textarea"
              :value="trip.destination"
              @input="trip.destination = $event.target.value"
          ></textarea>
          <template v-else>
            <view class="cascade-selector" @click="openCascadeSelector('destination', index)">
              <text class="selected-value">
                {{ trip.destinationProvince && trip.destinationCity && trip.destinationDistrict
                  ? `${trip.destinationProvince}-${trip.destinationCity}-${trip.destinationDistrict}`
                  : '请选择省/市/区' }}
              </text>
              <text class="select-icon">▼</text>
            </view>
          </template>
        </view>

        <!-- 出发时间 -->
        <view class="form-item">
          <text class="label">出发时间*</text>
          <textarea
              placeholder="请输入日期时间"
              class="textarea"
              :value="trip.departureTime"
              @input="trip.departureTime = $event.target.value"
          ></textarea>
        </view>

        <!-- 到达时间 -->
        <view class="form-item">
          <text class="label">到达时间*</text>
          <textarea
              placeholder="请输入日期时间"
              class="textarea"
              :value="trip.arrivalTime"
              @input="trip.arrivalTime = $event.target.value"
          ></textarea>
        </view>
      </view>

      <!-- 添加行程按钮 -->
      <view class="add-trip-area" @click="addTrip">
        <view class="add-btn">+</view>
        <text class="add-tip">添加新行程（最多10个）</text>
      </view>
    </view>

    <!-- 离校信息区域 -->
    <view class="form-section">
      <view class="form-item">
        <text class="label">计划离校时间*</text>
        <textarea
            placeholder="请输入离校时间"
            class="textarea"
            :value="planLeaveTime"
            @input="planLeaveTime = $event.target.value"
        ></textarea>
      </view>
      <view class="form-item">
        <text class="label">计划到达时间*</text>
        <textarea
            placeholder="请输入到达目的地时间"
            class="textarea"
            :value="planArriveTime"
            @input="planArriveTime = $event.target.value"
        ></textarea>
      </view>
      <view class="form-item">
        <text class="label">离校目的地*</text>
        <textarea
            placeholder="请选择省/市/区(县)"
            class="textarea"
            :value="destinationArea"
            @input="destinationArea = $event.target.value"
        ></textarea>
        <textarea
            placeholder="请输入详细地址到门牌号"
            class="textarea"
            style="margin-top: 8px;"
            :value="destinationDetail"
            @input="destinationDetail = $event.target.value"
        ></textarea>
      </view>
      <view class="form-item">
        <text class="label">紧急联系人姓名*</text>
        <textarea
            placeholder="请输入紧急联系人姓名"
            class="textarea"
            :value="emergencyContact"
            @input="emergencyContact = $event.target.value"
        ></textarea>
      </view>
      <view class="form-item">
        <text class="label">紧急联系人电话*</text>
        <textarea
            placeholder="请输入紧急联系人手机号"
            class="textarea"
            :value="emergencyPhone"
            @input="emergencyPhone = $event.target.value"
        ></textarea>
      </view>
      <view class="form-item">
        <text class="label">其他说明：</text>
        <textarea
            placeholder="请输入特殊情况说明（如无则不填）"
            class="textarea"
            :value="otherDesc"
            @input="otherDesc = $event.target.value"
        ></textarea>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-btn" @click="submitApply">提交申请</view>

    <!-- 交通工具选择弹窗 -->
    <view class="popup-mask" v-if="showTransportDict" @click="showTransportDict = false"></view>
    <view class="transport-popup" v-if="showTransportDict">
      <view class="popup-title">选择交通工具</view>
      <view class="dict-list">
        <view
            class="dict-item"
            v-for="(item, index) in transportDict"
            :key="index"
            @click="selectTransport(item)"
        >
          {{ item }}
        </view>
      </view>
    </view>

    <!-- 省市区级联选择弹窗 -->
    <view class="popup-mask" v-if="showCascadeSelector" @click="closeCascadeSelector"></view>
    <view class="cascade-popup" v-if="showCascadeSelector">
      <view class="popup-title">
        <text>选择地区</text>
        <text class="close-btn" @click="closeCascadeSelector">×</text>
      </view>

      <view class="cascade-content">
        <view class="cascade-column">
          <view
              class="cascade-item"
              v-for="(province, pIndex) in provinces"
              :key="pIndex"
              :class="{ active: currentProvince === province }"
              @click="selectProvince(province)"
          >
            {{ province }}
          </view>
        </view>

        <view class="cascade-column">
          <view
              class="cascade-item"
              v-for="(city, cIndex) in cities"
              :key="cIndex"
              :class="{ active: currentCity === city }"
              @click="selectCity(city)"
          >
            {{ city }}
          </view>
        </view>

        <view class="cascade-column">
          <view
              class="cascade-item"
              v-for="(district, dIndex) in districts"
              :key="dIndex"
              :class="{ active: currentDistrict === district }"
              @click="selectDistrict(district)"
          >
            {{ district }}
          </view>
        </view>
      </view>

      <view class="cascade-confirm" @click="confirmCascadeSelection">
        确认选择
      </view>
    </view>
  </view>
</template>

<script setup>
import { useRouter } from 'vue-router';
import { ref, reactive } from 'vue';  // 移除了watch的导入
import { store } from '@/store';

const goToPage3 = () => {
  router.push('/pages/students/page3');
};

const goToPage4 = () => {
  // 这里假设返校登记页面为page4，实际根据需求调整
  router.push('/pages/students/page4');
};

const goToPage2 = (type) => {
  // 可以根据需要传递参数区分不同类型的离校申请
  router.push('/pages/students/page2');
};

const router = useRouter();

// 交通工具内置字典
const transportDict = ref([
  '西安咸阳国际机场',
  '高铁西安北站',
  '火车西安站',
  '火车西安南站',
  '汽车站',
  '其他'
]);

// 省市区数据
const provinces = ref([
  '北京市', '上海市', '广东省', '江苏省', '陕西省', '四川省',
  '浙江省', '山东省', '河南省', '河北省', '湖南省', '湖北省'
]);
const cities = ref([]);
const districts = ref([]);

// 省市区数据映射
const areaData = reactive({
  '陕西省': {
    '西安市': ['未央区', '新城区', '碑林区', '莲湖区', '灞桥区', '雁塔区', '阎良区', '临潼区', '长安区'],
    '宝鸡市': ['渭滨区', '金台区', '陈仓区'],
    '咸阳市': ['秦都区', '渭城区', '兴平市']
  },
  '广东省': {
    '广州市': ['越秀区', '海珠区', '荔湾区', '天河区', '白云区'],
    '深圳市': ['福田区', '罗湖区', '南山区', '宝安区', '龙岗区']
  },
  '北京市': {
    '北京市': ['东城区', '西城区', '朝阳区', '海淀区', '丰台区', '石景山区']
  },
  '上海市': {
    '上海市': ['黄浦区', '徐汇区', '长宁区', '静安区', '普陀区', '虹口区']
  }
});

// 行程数据
const trips = ref([{
  id: 1,
  transport: '',
  transportInfo: '',
  departure: '',
  destination: '',
  departureTime: '',
  arrivalTime: '',
  departureProvince: '',
  departureCity: '',
  departureDistrict: '',
  destinationProvince: '',
  destinationCity: '',
  destinationDistrict: ''
}]);

// 离校信息数据
const planLeaveTime = ref('');
const planArriveTime = ref('');
const destinationArea = ref('');
const destinationDetail = ref('');
const emergencyContact = ref('');
const emergencyPhone = ref('');
const otherDesc = ref('');

// 级联选择器状态
const showCascadeSelector = ref(false);
const currentType = ref('');
const currentIndex = ref(-1);
const currentProvince = ref('');
const currentCity = ref('');
const currentDistrict = ref('');

// 交通工具选择状态
const selectedTransport = ref('');
const showTransportDict = ref(false);

// 删除原有的watch监听代码
// 监听省份变化
// watch(currentProvince, (newVal) => { ... });

// 监听城市变化
// watch(currentCity, (newVal) => { ... });

// 返回上一页
const goBack = () => {
  router.push('/pages/students/page1');
};

// 添加行程
const addTrip = () => {
  if (trips.value.length < 10) {
    const newTripId = trips.value.length + 1;
    trips.value.push({
      id: newTripId,
      transport: '',
      transportInfo: '',
      departure: '',
      destination: '',
      departureTime: '',
      arrivalTime: '',
      departureProvince: '',
      departureCity: '',
      departureDistrict: '',
      destinationProvince: '',
      destinationCity: '',
      destinationDistrict: ''
    });
    uni.showToast({
      title: `已添加行程信息${newTripId}`,
      icon: 'none',
      duration: 1500
    });
  } else {
    uni.showToast({
      title: '最多只能添加10个行程',
      icon: 'none',
      duration: 1500
    });
  }
};

// 删除行程
const removeTrip = (index) => {
  if (trips.value.length > 1) {
    trips.value.splice(index, 1);
    trips.value.forEach((trip, i) => {
      trip.id = i + 1;
    });
    uni.showToast({
      title: '已删除该行程',
      icon: 'none',
      duration: 1500
    });
  } else {
    uni.showToast({
      title: '至少需保留1个行程信息',
      icon: 'none',
      duration: 1500
    });
  }
};

// 选择交通工具
const selectTransport = (item) => {
  selectedTransport.value = item;
  showTransportDict.value = false;
};

// 打开级联选择器
const openCascadeSelector = (type, index) => {
  currentType.value = type;
  currentIndex.value = index;
  const trip = trips.value[index];

  if (type === 'departure') {
    currentProvince.value = trip.departureProvince || provinces.value[0];
    currentCity.value = trip.departureCity || '';
    currentDistrict.value = trip.departureDistrict || '';
  } else {
    currentProvince.value = trip.destinationProvince || provinces.value[0];
    currentCity.value = trip.destinationCity || '';
    currentDistrict.value = trip.destinationDistrict || '';
  }

  // 手动初始化城市和区县数据
  if (currentProvince.value && areaData[currentProvince.value]) {
    cities.value = Object.keys(areaData[currentProvince.value]);
    if (!currentCity.value && cities.value.length > 0) {
      currentCity.value = cities.value[0];
    }
  } else {
    cities.value = [];
    currentCity.value = '';
  }

  if (currentProvince.value && currentCity.value && areaData[currentProvince.value][currentCity.value]) {
    districts.value = areaData[currentProvince.value][currentCity.value];
    if (!currentDistrict.value && districts.value.length > 0) {
      currentDistrict.value = districts.value[0];
    }
  } else {
    districts.value = [];
    currentDistrict.value = '';
  }

  showCascadeSelector.value = true;
};

// 关闭级联选择器
const closeCascadeSelector = () => {
  showCascadeSelector.value = false;
};

// 选择省份（修改为手动更新城市和区县）
const selectProvince = (province) => {
  currentProvince.value = province;
  // 手动更新城市数据
  if (province && areaData[province]) {
    cities.value = Object.keys(areaData[province]);
    currentCity.value = cities.value[0] || '';
    // 手动更新区县数据
    if (currentCity.value) {
      districts.value = areaData[province][currentCity.value] || [];
      currentDistrict.value = districts.value[0] || '';
    } else {
      districts.value = [];
      currentDistrict.value = '';
    }
  } else {
    cities.value = [];
    currentCity.value = '';
    districts.value = [];
    currentDistrict.value = '';
  }
};

// 选择城市（修改为手动更新区县）
const selectCity = (city) => {
  currentCity.value = city;
  // 手动更新区县数据
  if (currentProvince.value && city && areaData[currentProvince.value][city]) {
    districts.value = areaData[currentProvince.value][city];
    currentDistrict.value = districts.value[0] || '';
  } else {
    districts.value = [];
    currentDistrict.value = '';
  }
};

// 选择区县
const selectDistrict = (district) => {
  currentDistrict.value = district;
};

// 确认地区选择
const confirmCascadeSelection = () => {
  if (!currentProvince.value || !currentCity.value || !currentDistrict.value) {
    uni.showToast({
      title: '请完整选择省/市/区',
      icon: 'none',
      duration: 1500
    });
    return;
  }

  const trip = trips.value[currentIndex.value];
  if (currentType.value === 'departure') {
    trip.departureProvince = currentProvince.value;
    trip.departureCity = currentCity.value;
    trip.departureDistrict = currentDistrict.value;
  } else {
    trip.destinationProvince = currentProvince.value;
    trip.destinationCity = currentCity.value;
    trip.destinationDistrict = currentDistrict.value;
  }

  showCascadeSelector.value = false;
};

// 提交申请
const submitApply = () => {
  // 提交逻辑不变，此处省略
  if (!selectedTransport.value) {
    uni.showToast({
      title: '请为行程信息一选择交通工具',
      icon: 'none',
      duration: 1500
    });
    return;
  }

  // 其他验证逻辑...

  uni.showToast({
    title: '提交成功',
    icon: 'success',
    duration: 2000
  });

  store.updateStatus('processing','leave');

  setTimeout(() => {
    router.push('/pages/students/page1');
  }, 2000);
};
</script>


<style scoped>
.leave-school-apply {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 80px;
}

.back-area {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  cursor: pointer;
}
.back-icon {
  font-size: 22px;
  color: #409eff;
  margin-right: 8px;
}
.back-text {
  font-size: 16px;
  color: #409eff;
  font-weight: 500;
}

.tip-bar {
  background-color: #f0ad4e;
  color: #fff;
  padding: 12px;
  text-align: center;
  font-size: 14px;
}

.tabs {
  display: flex;
  background-color: #fff;
  border-bottom: 1px solid #e5e5e5;
}
.tab-item {
  flex: 1;
  text-align: center;
  padding: 16px 0;
  font-size: 16px;
  color: #666;
  position: relative;
  cursor: pointer;
}
.tab-item.active {
  color: #409eff;
}
.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 25%;
  width: 50%;
  height: 2px;
  background-color: #409eff;
}

.trip-container {
  padding: 0 15px;
  margin-top: 15px;
}

.trip-card {
  margin-bottom: 15px;
  padding: 18px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}
.trip-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}
.minus-btn {
  width: 32px;
  height: 32px;
  background-color: #f56c6c;
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  cursor: pointer;
}
.section-desc {
  font-size: 13px;
  color: #888;
  margin-bottom: 18px;
  display: block;
}

.add-trip-area {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 15px 0;
  margin-bottom: 15px;
  background-color: #fff;
  border-radius: 5px;
  cursor: pointer;
}
.add-btn {
  width: 36px;
  height: 36px;
  background-color: #409eff;
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  margin-right: 12px;
}
.add-tip {
  font-size: 15px;
  color: #409eff;
}

.form-section {
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  padding: 18px;
  margin: 0 15px 15px;
}
.form-item {
  margin-bottom: 18px;
}
.form-item:last-child {
  margin-bottom: 0;
}
.label {
  display: block;
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
}
.textarea {
  width: 100%; /* 设置宽度为354px */
  height: 32px; /* 设置高度为32px */
  padding: 6px 15px; /* 减少垂直内边距，避免内容溢出 */
  border: 1px solid #e5e5e5;
  border-radius: 4px;
  font-size: 14px;
  color: #333;
  min-height: auto; /* 取消最小高度限制 */
  resize: none; /* 禁止调整大小，保持固定尺寸 */
  box-sizing: border-box; /* 确保padding和border包含在设置的尺寸内 */
  line-height: 1; /* 调整行高，使内容垂直居中 */
}
.textarea::placeholder {
  color: #c0c4cc;
}

.submit-btn {
  background-color: #409eff;
  color: #fff;
  text-align: center;
  padding: 15px;
  margin: 0 15px 20px;
  border-radius: 5px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
}

.dict-selector, .cascade-selector {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #e5e5e5;
  border-radius: 4px;
  font-size: 14px;
  color: #333;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  cursor: pointer;
  min-height: 50px; /* 与textarea保持一致高度 */
}
.select-icon {
  color: #c0c4cc;
  font-size: 12px;
}

.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
}
.transport-popup {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  z-index: 1000;
  padding: 15px;
}
.popup-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  padding: 10px 0;
  text-align: center;
  border-bottom: 1px solid #e5e5e5;
  position: relative;
}
.close-btn {
  position: absolute;
  right: 15px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 20px;
  color: #999;
  cursor: pointer;
}
.dict-list {
  max-height: 300px;
  overflow-y: auto;
}
.dict-item {
  padding: 15px;
  font-size: 15px;
  color: #333;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
}

.cascade-popup {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
  z-index: 1000;
  max-height: 80vh;
}
.cascade-content {
  display: flex;
  height: calc(100% - 100px);
  min-height: 300px;
}
.cascade-column {
  flex: 1;
  overflow-y: auto;
  border-right: 1px solid #f5f5f5;
}
.cascade-column:last-child {
  border-right: none;
}
.cascade-item {
  padding: 15px;
  font-size: 14px;
  color: #333;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
}
.cascade-item.active {
  background-color: #e8f4fd;
  color: #409eff;
}
.cascade-confirm {
  padding: 15px;
  background-color: #409eff;
  color: #fff;
  text-align: center;
  font-size: 16px;
  cursor: pointer;
}
</style>
